/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Persistencia;

import Persistencia.exceptions.NonexistentEntityException;
import Persistencia.exceptions.PreexistingEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import motoressa.Vehiculo;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.UserTransaction;
import motoressa.Segmento;

/**
 *
 * @author HP
 */
public class SegmentoJpaController implements Serializable {

    public SegmentoJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public SegmentoJpaController() {
        emf=Persistence.createEntityManagerFactory("MotoresSAPU");
    }
    

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Segmento segmento) throws PreexistingEntityException, Exception {
        if (segmento.getMisVehiculos() == null) {
            segmento.setMisVehiculos(new ArrayList<Vehiculo>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Vehiculo> attachedMisVehiculos = new ArrayList<Vehiculo>();
            for (Vehiculo misVehiculosVehiculoToAttach : segmento.getMisVehiculos()) {
                misVehiculosVehiculoToAttach = em.getReference(misVehiculosVehiculoToAttach.getClass(), misVehiculosVehiculoToAttach.getNumeroPatente());
                attachedMisVehiculos.add(misVehiculosVehiculoToAttach);
            }
            segmento.setMisVehiculos(attachedMisVehiculos);
            em.persist(segmento);
            for (Vehiculo misVehiculosVehiculo : segmento.getMisVehiculos()) {
                Segmento oldMiSegmentoOfMisVehiculosVehiculo = misVehiculosVehiculo.getMiSegmento();
                misVehiculosVehiculo.setMiSegmento(segmento);
                misVehiculosVehiculo = em.merge(misVehiculosVehiculo);
                if (oldMiSegmentoOfMisVehiculosVehiculo != null) {
                    oldMiSegmentoOfMisVehiculosVehiculo.getMisVehiculos().remove(misVehiculosVehiculo);
                    oldMiSegmentoOfMisVehiculosVehiculo = em.merge(oldMiSegmentoOfMisVehiculosVehiculo);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findSegmento(segmento.getCodigo()) != null) {
                throw new PreexistingEntityException("Segmento " + segmento + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Segmento segmento) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Segmento persistentSegmento = em.find(Segmento.class, segmento.getCodigo());
            List<Vehiculo> misVehiculosOld = persistentSegmento.getMisVehiculos();
            List<Vehiculo> misVehiculosNew = segmento.getMisVehiculos();
            List<Vehiculo> attachedMisVehiculosNew = new ArrayList<Vehiculo>();
            for (Vehiculo misVehiculosNewVehiculoToAttach : misVehiculosNew) {
                misVehiculosNewVehiculoToAttach = em.getReference(misVehiculosNewVehiculoToAttach.getClass(), misVehiculosNewVehiculoToAttach.getNumeroPatente());
                attachedMisVehiculosNew.add(misVehiculosNewVehiculoToAttach);
            }
            misVehiculosNew = attachedMisVehiculosNew;
            segmento.setMisVehiculos(misVehiculosNew);
            segmento = em.merge(segmento);
            for (Vehiculo misVehiculosOldVehiculo : misVehiculosOld) {
                if (!misVehiculosNew.contains(misVehiculosOldVehiculo)) {
                    misVehiculosOldVehiculo.setMiSegmento(null);
                    misVehiculosOldVehiculo = em.merge(misVehiculosOldVehiculo);
                }
            }
            for (Vehiculo misVehiculosNewVehiculo : misVehiculosNew) {
                if (!misVehiculosOld.contains(misVehiculosNewVehiculo)) {
                    Segmento oldMiSegmentoOfMisVehiculosNewVehiculo = misVehiculosNewVehiculo.getMiSegmento();
                    misVehiculosNewVehiculo.setMiSegmento(segmento);
                    misVehiculosNewVehiculo = em.merge(misVehiculosNewVehiculo);
                    if (oldMiSegmentoOfMisVehiculosNewVehiculo != null && !oldMiSegmentoOfMisVehiculosNewVehiculo.equals(segmento)) {
                        oldMiSegmentoOfMisVehiculosNewVehiculo.getMisVehiculos().remove(misVehiculosNewVehiculo);
                        oldMiSegmentoOfMisVehiculosNewVehiculo = em.merge(oldMiSegmentoOfMisVehiculosNewVehiculo);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                int id = segmento.getCodigo();
                if (findSegmento(id) == null) {
                    throw new NonexistentEntityException("The segmento with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(int id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Segmento segmento;
            try {
                segmento = em.getReference(Segmento.class, id);
                segmento.getCodigo();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The segmento with id " + id + " no longer exists.", enfe);
            }
            List<Vehiculo> misVehiculos = segmento.getMisVehiculos();
            for (Vehiculo misVehiculosVehiculo : misVehiculos) {
                misVehiculosVehiculo.setMiSegmento(null);
                misVehiculosVehiculo = em.merge(misVehiculosVehiculo);
            }
            em.remove(segmento);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Segmento> findSegmentoEntities() {
        return findSegmentoEntities(true, -1, -1);
    }

    public List<Segmento> findSegmentoEntities(int maxResults, int firstResult) {
        return findSegmentoEntities(false, maxResults, firstResult);
    }

    private List<Segmento> findSegmentoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Segmento as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Segmento findSegmento(int id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Segmento.class, id);
        } finally {
            em.close();
        }
    }

    public int getSegmentoCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Segmento as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
